<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="88px">
      <el-form-item label="固件版本号" prop="versionNO">
        <el-input v-model.trim="queryParams.versionNO" placeholder="请输入固件版本号" clearable style="width: 240px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="适用设备型号" prop="types" label-width="100">
        <el-select v-model="queryParams.types" style="width: 240px;" clearable placeholder="请选择设备型号" @change="getList">
            <el-option v-for="item in options1" :key="item.id" :label="item.entName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Upload" @click="handleImport">新增固件</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>
     <!-- 表格数据 -->
     <el-table v-loading="loading" size="large" :max-height="tableHeight" :data="dataList">
      <el-table-column type="index" label="序号" width="120" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="固件名称"  v-if="columns[0].visible" prop="versionName" align="center" width="200" />
      <el-table-column label="固件版本号"  v-if="columns[1].visible" prop="versionNO" align="center" width="100" />
      <el-table-column label="适用设备型号"  v-if="columns[2].visible" prop="types" align="center" width="150" />
      <el-table-column label="固件存放路径"  v-if="columns[3].visible" prop="filePath" align="center" width="200" />
      <el-table-column label="固件文件大小" v-if="columns[4].visible" prop="fileSize" align="center" width="150" />
      <el-table-column label="版本说明" v-if="columns[5].visible" prop="versionFeatures" align="center" width="200" />
      <el-table-column fixed="right" label="操作" align="center" min-width="240px" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="download" @click="handleExport(scope.row)">下载固件</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef" v-if="form.filePath" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="固件名称" prop="versionName">
          <el-input v-model.trim="form.versionName" maxlength="30" placeholder="请输入固件名称" />
        </el-form-item>
        <el-form-item label="固件版本号" prop="versionNO">
          <el-input v-model.trim="form.versionNO" maxlength="30" placeholder="1.0.0" />
        </el-form-item>
        <el-form-item label="适用设备型号" prop="types">
          <el-select v-model="form.types" multiple>
            <el-option v-for="item in options1" :key="item.id" :label="item.entName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="固件存放路径" prop="filePath">
          <el-input v-model.trim="form.filePath" maxlength="30" disabled placeholder="固件存放路径" />
        </el-form-item>
        <el-form-item label="固件存放大小" prop="fileSize">
          <el-input v-model.trim="form.fileSize" maxlength="30" disabled placeholder="固件存放大小" />
        </el-form-item>
        <el-form-item label="版本说明" prop="versionFeatures">
          <el-input v-model.trim="form.versionFeatures" maxlength="30" type="textarea" placeholder="版本说明" />
        </el-form-item>
      </el-form>
      <el-upload v-else ref="uploadRef" :limit="1"  :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading"  :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">请先选择固件文件，拖到此处或<em>点击上传</em></div>
      </el-upload>
      <template #footer>
        <div class="dialog-footer" v-if="form.filePath">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Role">
import { getToken } from "@/utils/auth";
import { tansParams, blobValidate } from '@/utils/ruoyi'
import { saveAs } from 'file-saver'
// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const tableHeight = ref(document.documentElement.scrollHeight - 280 + "px");

const { proxy } = getCurrentInstance();
const dataInfo = ref([]);
const total = ref(0);
const dataList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const uploadRef = ref(null);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const fileInfo = ref({
});
const options1 = ref([
  { id: '600', entName: "600" },
  { id: '700', entName: "700" },
  { id: '700B', entName: "700B" },
  { id: '700F', entName: "700F" },
  { id: '800', entName: "800" },
  { id: '810', entName: "810" },
  { id: '811', entName: "811" },
  { id: '820', entName: "820" },
  { id: '888', entName: "888" },
  { id: '900B', entName: "900B" },
  { id: '900D', entName: "900D" },
]);
// 列显隐信息
const columns = ref([
  { key: 1, label: `固件名称`, visible: true },
  { key: 2, label: `固件版本号`, visible: true },
  { key: 3, label: `使用设备型号`, visible: true },
  { key: 4, label: `固件存放路径`, visible: true },
  { key: 5, label: `固件文件大小(KB)`, visible: true },
  { key: 6, label: `版本说明`, visible: true },
]);
const data = reactive({
  form: {
    id: null,
    versionName: null,//固件版名称
    versionNO: null,//固件版本号
    types: null,//下拉适用设备型号
    filePath: null,//固件存放路径
    fileSize: null,//固件文件大小：KB
    versionFeatures: null,//版本说明
  },
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    versionNO: null,//'固件版本号'
    types: null,//适用123
  },
  rules: {
    versionName: [{ required: true, message: "固件名称不能为空", trigger: "blur" }],
    versionNO: [{ required: true, message: "固件版本号不能为空", trigger: "blur" }],
    types: [{ required: true, message: "适用设备型号不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/api/Upload/UploadFirmware"
});

// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
  clearTimeout(timer);
  timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}


/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除固件名称"' + row.versionName + '"的数据项?').then(function () {
    proxy.cloudTv_API.DelVersion({
        id: row.id,
      }).then(response => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      });
  })
}

/** 新增 */
function handleImport() {
  reset();
  upload.title = "新增固件";
  upload.open = true;
    // 清空上传组件的文件列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
   // 确保上传状态重置为可上传
   upload.isUploading = false; 
};

/** 下载 */
function handleExport(row) {
  let name = row.versionName + '.' + row.filePath.split('.').pop();
  proxy.cloudTv_API.DownFirmware({FileName:row.reName}).then(async data => {
    const isBlob = blobValidate(data);
    const blob = new Blob([data])
    saveAs(blob, name)
  })
}

/** 修改 */
function handleUpdate(row) {
  let newRow = JSON.parse(JSON.stringify(row));
  reset();
  Object.keys(form.value).forEach(key => {
    form.value[key] = newRow[key];
  });
  upload.title = "修改固件";
  upload.open = true;
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    id: null,
    versionName: null,//固件版名称
    versionNO: null,//固件版本号
    types: null,//下拉适用设备型号
    filePath: null,//固件存放路径
    fileSize: null,//固件文件大小：KB
    versionFeatures: null,//版本说明
  };
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  proxy.$refs["uploadRef"].handleRemove(file);
  if (response.code == 1) {
     form.value.versionName = response?.data?.fileName.split('.')[0] || null;
     form.value.filePath = response?.data?.reName;
     form.value.fileSize = Math.floor(response?.data?.fileSize / 1024)+'KB';
     console.log(form.value);
  }else{
    proxy.$message.error(response.message);
  }
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        proxy.cloudTv_API.EditVersion({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          upload.open = false;
          getList();
        });
      } else {
        proxy.cloudTv_API.AddVersion({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          upload.open = false;
          getList();
        });
      }
    }
  });
};

/** 查询列表 */
function getList() {
  loading.value = true;
  proxy.cloudTv_API.GetVersionPageList(queryParams.value).then(response => {
    dataList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}

getList();
</script>

<style lang="scss" scoped>
</style>
